package com.hae.shop.common.util;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.constant.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * 全局统一异常处理能
 * 若使用ControllerAdvice，需要为每个方法加上@ResponseBody
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlerUtil {

    /**
     * bean 参数校验统一处理
     * SpringBoot配置了默认异常处理器DefaultHandlerExceptionResolver，而该处理器仅仅是将异常信息打印出来，因此需要单独处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<?> validationErrorHandler(MethodArgumentNotValidException ex) {
        Response<?> response = new Response<>();
        // 如果前面开启了fail_fast，事实上这里只会有一个信息
        //如果没有，则可能又多个
        List<ObjectError> violations = ex.getBindingResult().getAllErrors();
        response.setErrorCode(ErrorEnum.PARAMS_VALIDATE_EXCEPTION.getErrorCode());
            response.setErrorMsg(violations.get(0).getDefaultMessage());
        return response;
    }

    /**
     * 运行是异常统一处理
     */
    @ExceptionHandler(RuntimeException.class)
    public Response exceptionHandler(Exception e) {
        Response response = new Response();
       // requestParam参数校验
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                response.setErrorCode(ErrorEnum.PARAMS_VALIDATE_EXCEPTION.getErrorCode());
                response.setErrorMsg(item.getMessage());
                break;
            }
        } else {
            log.info("###全局捕获异常###,error:{}", e);
            response.setErrorCode(ErrorEnum.SYSTEM_INNER_EXCEPTION.getErrorCode());
            response.setErrorMsg(ErrorEnum.SYSTEM_INNER_EXCEPTION.getErrorMsg());
        }
        return response;
    }

}
